package com.dingdang.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingdang.data.Result;
import com.dingdang.dto.UserDTO;
import com.dingdang.entity.TbCarGoods;
import com.dingdang.mapper.TbCarGoodsThreeMapper;
import com.dingdang.service.EsService;
import com.dingdang.service.impl.EsServiceImpl;
import com.dingdang.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import com.dingdang.service.EsService;
import com.dingdang.utils.JwtUtil;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("hot")
@Api("热度排行")

public class HotController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TbCarGoodsThreeMapper tbCarGoodsMapper;

    @Autowired
    private EsService esService;


    @PutMapping("addHot")
    @ApiOperation(value = "静态页面热度推荐")
    @ApiImplicitParam(name = "carId", value = "静态页面Id", required = true, paramType = "query")
    public Result  addHot(@RequestParam("carId") Long carId, HttpServletRequest request){
        ZSetOperations zSetOperations = redisTemplate.opsForZSet();
        String key = "hot:pv";
        String value = carId.toString();
        zSetOperations.incrementScore(key,value,1);

        //------------分割线------------//
        TbCarGoods tbCarGoods = esService.selectById(carId);
        String labelId = tbCarGoods.getLabelId();
        //去头去尾部以后使用逗号分割
        //将标签存入redis中Zset key=user+用户的id  value 时间戳/10000 分数
        List<Integer> list = JSONObject.parseObject(labelId, List.class);
        //String str = labelId.substring(1, labelId.length() - 1);
        //String[] split = str.split(",");
        String authToken = request.getHeader("authToken");
        Claims claims = jwtUtil.parseJwt(authToken);
        String subject = claims.getSubject();
        UserDTO userDTO = JSONObject.parseObject(subject, UserDTO.class);
        System.out.println(userDTO);
        Long uid = userDTO.getUid();
        ZSetOperations zSet = redisTemplate.opsForZSet();

        for (Integer integer : list) {
            zSet.incrementScore("userTime" + uid, String.valueOf(integer),new Date().getTime()/10000);
            zSet.incrementScore("user" + uid, String.valueOf(integer),1);
        }

//        for (int i = 0; i <split.length ; i++) {
//            zSet.incrementScore("user" + uid, split[i],new Date().getTime()/10000);
//            zSet.incrementScore("user" + uid, split[i],1);
//        }

        return Result.ok();
    }
    @PostMapping("getHot")
    @ApiOperation(value = "热度排行查询")
    public Result getHot(){
        List<Integer> list = new ArrayList();
        String key = "hot:pv";
        ZSetOperations zSet = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple<Object>> set = zSet.reverseRangeWithScores(key, 0, 10);
        Iterator<ZSetOperations.TypedTuple<Object>> iterator = set.iterator();
        while (iterator.hasNext()){
            ZSetOperations.TypedTuple<Object> next = iterator.next();
            System.out.println(next.getValue());
            String  carId = (String) next.getValue();
            Integer integer = Integer.valueOf(carId);
            list.add(integer);
        }
        List<TbCarGoods> list1 = tbCarGoodsMapper.selecByList(list);
        return Result.ok().setData(list1);
    }

    //删除redis中的zset方法(定时器)
    @Scheduled(cron = "* * 1 * * ?")
    public void delRedisZSet(){
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        response.setContentType("text/html;charset=utf-8");
        String authToken = response.getHeader("authToken");
        Claims claims = jwtUtil.parseJwt(authToken);
        String subject = claims.getSubject();
        UserDTO userDTO = JSONObject.parseObject(subject, UserDTO.class);
        Boolean aBoolean = redisTemplate.hasKey("user" + userDTO.getUid());
        if (aBoolean){
            redisTemplate.delete("userTime" + userDTO.getUid());
        }else {
            System.out.println("删除成功");
        }
    }
}
